package apphttp

import (
	"net/http"

	"TanguyWeb/main/bean"
	"time"
	"TanguyWeb/main/utils/dbutil"
	"TanguyWeb/main/config"
	"TanguyWeb/main/session"
	"gitee.com/DengAnbang/goutils/loge"
)

/**
登陆
/app/user/login
loginType(0 密码 1 第三方)
phone
pwd
key
 */
func login(_ http.ResponseWriter, r *http.Request) error {
	loge.ENullable(r.ParseForm())
	values := r.Form
	loginType, phone, pwd, _ := values.Get("loginType"), values.Get("phone"), values.Get("pwd"), values.Get("key")
	checkEmpty(loginType, "请先选择登陆方式!")
	if loginType == "0" {
		checkEmpty(phone, "手机号不能为空!")
		checkEmpty(pwd, "密码不能为空!")
		rows, err := dbutil.Db.Query("SELECT * FROM user WHERE phone = ? AND pwd = ? LIMIT 1;", phone, pwd)
		checkErr(err)
		defer rows.Close()
		if rows.Next() {
			row, err := dbutil.GetRowsMap(rows)
			checkErr(err)
			userBean := bean.NewUserBean(row)
			session.LoginOut(string(userBean.UserID))
			newSession := session.NewSession()
			newSession.SetValue("user_id", userBean.UserID)
			userBean.SessionID = newSession.SessionID
			return bean.NewResultData(userBean)
		} else {
			return bean.NewResultError(config.Err, "密码错误!")
		}
	}
	return nil
}

/**
注册
/app/user/register
captcha
phone
sessionID
 */
func register(_ http.ResponseWriter, r *http.Request) error {
	loge.ENullable(r.ParseForm())
	checkSession, err := checkSession(r)
	values := r.Form
	checkErr(err)
	captchaSession, ok := checkSession.GetValue("captcha")
	captchaTimeSession, ok := checkSession.GetValue("captchaTime")
	phoneSession, ok := checkSession.GetValue("phone")
	if !ok {
		return bean.NewResultError(config.Err, "请先获取验证码!")
	}
	captcha, phone := values.Get("captcha"), values.Get("phone")
	checkEmpty(phone, "手机号不能为空!")
	checkEmpty(captcha, "验证码不能为空!")
	if captchaTime, ok := captchaTimeSession.(time.Time); ok {
		if captchaTime.Add(300 * time.Second).Before(time.Now()) {
			return bean.NewResultError(config.Err, "验证码错误!").SetDebugMeg("验证码超时")
		}
	}
	if captchaSession != captcha {
		return bean.NewResultError(config.Err, "验证码错误!").SetDebugMeg("验证码错误")
	}
	if phoneSession != phone {
		return bean.NewResultError(config.Err, "验证码错误!").SetDebugMeg("手机号不是请求的手机号")
	}
	//验证码正确了
	checkSession.DeleteValue("captcha", "captchaTime", "phone")
	rows, err := dbutil.Db.Query("SELECT 1 FROM user WHERE phone = ? LIMIT 1;", phone)
	checkErr(err)
	defer rows.Close()
	if rows.Next() {
		return bean.NewResultError(config.Err, "账号已经存在")
	}

	stmt, err := dbutil.Db.Prepare("INSERT INTO user (phone)VALUES(?)")
	checkErr(err)
	result, err := stmt.Exec(phone)
	line, err := result.RowsAffected()
	checkErr(err)
	if line == 1 {
		return bean.NewResultData("注册成功")
	} else {
		return bean.NewResultError(config.Err, "注册失败")
	}
	return nil
}
